package com.isoft.illustrationsdraw.controller;

import com.isoft.illustrationsdraw.Constants;
import com.isoft.illustrationsdraw.service.UserService;
import com.isoft.illustrationsdraw.entity.Message;
import com.isoft.illustrationsdraw.service.ChatService;
import com.isoft.illustrationsdraw.service.FileService;
import com.isoft.illustrationsdraw.service.JWTService;
import com.isoft.illustrationsdraw.service.MessageService;
import com.isoft.illustrationsdraw.service.EmailService;


import org.apache.catalina.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    private final ChatService chatService;
    private final FileService fileService;
    private final SimpMessagingTemplate messagingTemplate;
    private final JWTService jwtService;
    private final MessageService messageService;
    private final UserService userService;
    private final EmailService emailService;

    public ChatController(EmailService emailService, UserService userService, MessageService messageSerivce, JWTService jwtService, ChatService chatService, SimpMessagingTemplate messagingTemplate, FileService fileService) {
        this.chatService = chatService;
        this.userService = userService;
        this.emailService = emailService;
        this.messagingTemplate = messagingTemplate;
        this.fileService = fileService;
        this.jwtService = jwtService;
        this.messageService = messageSerivce;
    }


    // 发送消息并上传文件
    @PostMapping("/sendMessage")
    public String sendMessage(@RequestParam Long senderId, 
                              @RequestParam Long receiverId, 
                              @RequestParam String content,
                              @RequestParam(required = false) MultipartFile file) {
        try {
            // 创建消息对象
            Message message = new Message();
            message.setSenderId(senderId);
            message.setReceiverId(receiverId);
            message.setContent(content);
            message.setTimestamp(java.time.LocalDateTime.now());

            // 调用服务保存消息
            chatService.saveMessage(message, file);

            return "Message sent successfully!";
        } catch (IllegalArgumentException | IOException e) {
            e.printStackTrace();
            return "Error sending message: " + e.getMessage();
        }
    }

    // WebSocket 端点：用于接收和发送 STOMP 消息
    // 修改 WebSocket 路径
    @MessageMapping("/sendWebSocketMessage")
    public void handleMessage(Message message) {
        String receiverDestination = "/queue/messages/" + message.getReceiverId() + "&" + message.getSenderId();
        String senderDestination = "/queue/messages/" + message.getSenderId() + "&" + message.getReceiverId();
    
        if (message.getMediaUrl() != null) {
            message.setMediaUrl(fileService.convertToOnlinePath(message.getMediaUrl()));
        }

        var receiver = userService.getById(message.getReceiverId());
        var sender = userService.getById(message.getSenderId());
        String targetUrl = "http://10.2.3.104/chat/" + sender.getId();
        emailService.sendReminderMessage(receiver.getEmail(), sender.getNickname(), targetUrl);
        
        
    
        messagingTemplate.convertAndSend(receiverDestination, message);
        messagingTemplate.convertAndSend(senderDestination, message);
    }
    

    @GetMapping("/gethistory/{receiverId}")
    public ResponseEntity<?> getChatHistory(@RequestParam String token, @PathVariable Long receiverId, @RequestParam Integer page) {
        if (!jwtService.validateToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Constants.Error.INVALID_TOKEN); // 401 Unauthorized
        }
        Long senderId = jwtService.getUserIdFromToken(token);
        return ResponseEntity.ok(messageService.getHistoryMessage(senderId, receiverId, page));
    }
}
